import { Menu } from './../entitys/Menu';
import { Context } from "koa"
import { Body, BodyParam, Ctx, Delete, Get, JsonController, Param, Post, Put, QueryParam } from "routing-controllers";
import { Inject } from "typedi";
import MenuService from "../services/MenuService";
import Response from '../common/response';

@JsonController("/menu")
export class MenuController {
    @Inject()
    menuService: MenuService
    @Post()
    async addMenu(@Body() menu: Menu) {
        if (!menu.name) {
            return Response.BAD_REQUEST("name is required")
        }
        if (menu.sort == undefined) {
            return Response.BAD_REQUEST("sort is required")
        }
        if (!menu.type) {
            return Response.BAD_REQUEST("type is required")
        }
        if (menu.type == 1) {
            if (!menu.path) {
                return Response.BAD_REQUEST("path is required")
            }
        }
        await this.menuService.addMenu(menu)
        return Response.SUCCESS()
    }
    @Get("/getMenus")
    async getMenus(@Ctx() ctx: Context) {
        let menus = await this.menuService.getUserMenu(ctx.userInfo)
        return Response.SUCCESS(menus)
    }
    @Get("/getRouters")
    async getRouters(@Ctx() ctx: Context) {
        let routers = await this.menuService.getUserRouters(ctx.userInfo)
        return Response.SUCCESS(routers)
    }
    @Get("/tree")
    async getTree(@QueryParam("menuName") menuName: string) {
        let menuTree = await this.menuService.getMenuTree(menuName)
        return Response.SUCCESS(menuTree)
    }
    @Get("/getMenuById/:id")
    async getMenuById(@Param("id") id: number) {
        let menu = await this.menuService.getMenuById(id)
        return Response.SUCCESS(menu)
    }
    @Put()
    async updateMenu(@Body() menu: Menu) {
        if (!menu.id) {
            return Response.BAD_REQUEST(" id is required")
        }
        let isOk = await this.menuService.updateMenu(menu)
        if (!isOk) {
            return Response.BAD_REQUEST(" the　id of " + menu.id + "  does not exist")
        }
        return Response.SUCCESS()
    }
    @Delete("/:id")
    async delMenu(@Param("id") id: number) {
        try {
            await this.menuService.delMenu(id)
        } catch (error) {
            return Response.BAD_REQUEST(error.message)
        }
        return Response.SUCCESS()
    }
}